<template>
  <view class="page_root" data-page-name="auth" data-page-identification="b_j9st1n6175">
      
  </view>
</template>
<script setup>

  import {
    ref,reactive,toRaw,markRaw,
    watch,computed,
    onBeforeMount,onMounted,onBeforeUnmount,onUnmounted,onActivated,onDeactivated,getCurrentInstance
  } from "vue";
  import { useRoute } from 'vue-router';
  const route = useRoute();
  import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios';
  import { isEqual, cloneDeep, isNullOrEmpty, isEmptyArr, isArray, isNullOrUnDef, localGet, traversalTreeStructure, set, checkCaseCondition, throttle, merge, switchCase, dateParse, debounce } from '@/utils/index';
  import { CovertOptions, getChartsDataSourceConvert } from '@/utils/chart';
  import { propertyFormatByNumber, propertyFormatByPercentage, propertyFormatByDate } from '@/utils/format';
  import { FormFormat } from '@/utils/formFormat'
  import dayjs from 'dayjs';
  // import '@vueup/vue-quill/dist/vue-quill.snow.css';
  
  import { handleRedirect, permission } from '@/utils/common'
  import { onPullDownRefresh, onLoad, onReady, onShow, onHide, onPageScroll } from '@dcloudio/uni-app'
  


  // ---------------------------- 属性定义 ----------------------------
  const sourceId = "page50001883"

    // 是否显示菜单按钮
    const isMenuIconShow = false;
    // NAVIGATION_MENU
    const handleShowNavigation = ()=>{};


  const setTimeOutList = [];





  // ============================ 属性定义 ============================

  // ---------------------------- 元素数据引用 ----------------------------
  // 动态key的map
  const fieldTypeMap = {};
  // 动态key的map
  const refMap = {};

  const showState = reactive({

  })
  // ============================ 元素数据引用 ============================

  // ---------------------------- 数据 ----------------------------


  // ============================ 数据 ============================

  // ---------------------------- 方法 ----------------------------
  // ---------------------------- 页面数据 ----------------------------


  // ============================ 页面数据 ============================

  // ---------------------------- 响应 ----------------------------

  // ============================ 响应 ============================

  // ---------------------------- 函数 ----------------------------

  // 自定义函数 返回上一页
  const customFunction_goBack_k4z93223fy =  (...params) => {
    uni.navigateBack()
  }

  // ============================ 函数 ============================

  // ---------------------------- 页面参数 ----------------------------

  const pageParameter_state = reactive({
      'processInstanceId': undefined,
  })

  // ============================ 页面参数 ============================

  // ---------------------------- 组件事件处理方法 ----------------------------


  // ============================ 组件事件处理方法 ============================

  // ============================ 方法 ============================

  // ---------------------------- 生命周期 ----------------------------

  const pageScrollTop = ref(0)

  

  
  const routeOption = ref({})
  onLoad((option) => {
    routeOption.value = option;
  });
  onReady(() => {
    setPageParams(routeOption.value)
    // 设置表单的rule
    try{

    }catch{
        // do nothing
    }
  });
  // 图表刷新标记
  const uChartsReshowFlag = ref(false);
  onHide(() => { // 页面隐藏后标记置为false(如果不置为false无法触发图表更新)
      uChartsReshowFlag.value = false
  })
  onShow(() => {
      uChartsReshowFlag.value = true; // 页面激活后,标记置为true

      setPageParams(routeOption.value)
  })
  onPageScroll(e => {
      pageScrollTop.value = e.scrollTop
  });
  

  const setPageParams = (routerParam)=>{
    const pageParams = [{"dataType":"STRING","dependencies":[],"name":"processInstanceId"}];
    const strategyMap = {
      STRING: (param, paramValue) => {
        pageParameter_state[param.name] = paramValue;
      },
      BOOLEAN: (param, paramValue) => {
        if('true' === (paramValue || '').toLowerCase()) {
          pageParameter_state[param.name] = true
        } else if('false' === (paramValue || '').toLowerCase()) {
          pageParameter_state[param.name] = false
        } else {
          // TODO: 是否要支持toast
          console.error('参数传入错误！类型不匹配！');
        }
      },
      NUMBER: (param, paramValue) => {
        if (!isNaN(paramValue)) {
          pageParameter_state[param.name] = Number(paramValue);
        } else {
          // TODO: 是否要支持toast
          console.error('参数传入错误！类型不匹配！');
        }
      },
      ARRAY: (param, paramValue) => {
        if (isNullOrUnDef(paramValue) || !paramValue || paramValue=== 'undefined') { // default value
          pageParameter_state[param.name] = [];
        } else if(paramValue.trim().startsWith('[') && paramValue.trim().endsWith(']')) {
          try {
            pageParameter_state[param.name] = JSON.parse(decodeURI(paramValue));
          } catch (error) {
            console.error('参数解析失败 ',error);
          }
        } else {
          console.error('参数传入错误！类型不匹配！');
        }
      },
    };
    pageParams.forEach((param) => {
      strategyMap[param.dataType](param, routerParam[param.name])
    });


  }

  onUnmounted(() => {
    // 销毁定时器
    setTimeOutList.forEach(({ repeat, timer }) => {
      repeat ?  clearInterval(timer): clearTimeout(timer);
    });
  });


  
  onPullDownRefresh(() => {
    // 下拉刷新
    setTimeout(() => {
        uni.stopPullDownRefresh()
    }, 1000)
  })
  

  // ============================ 生命周期 ============================

  // ---------------------------- 数据关联处理 ----------------------------
  // ---------------------------- 组件数据同步 ----------------------------

  // ============================ 组件数据同步 ============================
  //
  // ============================ 数据关联处理 ============================

  // ---------------------- 不同组件自定义的处理逻辑 ---------------------

  // ====================== 不同组件自定义的处理逻辑 ======================


  // ================================定制化逻辑========================================
  import {
    onBeforeRouteLeave
  } from 'vue-router';
  console.log(onBeforeRouteLeave, 'onBeforeRouteLeave');
  const stateForm = reactive({
    tenantId: null,
    sessionKey: null,
    userId: null,
    mobile: null,
    productId: null
  });
  var currentURL = window.location.href;

  function getParameterByName(name, url = window.location.href) {
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
      results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
  }

  stateForm.sessionKey = getParameterByName('sessionKey', currentURL);
  stateForm.userId = getParameterByName('userId', currentURL);
  stateForm.mobile = getParameterByName('mobile', currentURL);
  async function getTenantId() {
    try {
      let firstSlashIndex = currentURL.indexOf('/', 8);
      let prefix;

      if (firstSlashIndex !== -1) {
        prefix = currentURL.substring(0, firstSlashIndex);
        let protocols = ['http://', 'https://'];
        let protocol = protocols.find(p => prefix.includes(p));

        if (protocol) {
          let result = prefix.substring(protocol.length);
          result = result + '/app_50000005/';
          console.log(result, 'result');
          let data = await post(`${prefix}/base/api/v1/product/url`, {
            url: result
          });
          if (data.status === 'success') {
            stateForm.tenantId = data.data.tenantId;
            stateForm.productId = data.data.id;
            console.log(stateForm.tenantId, 'stateForm.tenantId');
            getUser();
          } else {
            console.error('获取tenantId失败');
          }
        } else {
          console.error('未找到 `http://` 或 `https://`');
        }
      } else {
        console.error('无法提取前缀');
      }
    } catch (error) {
      console.error('getTenantId出现错误:', error);
    }
  }

  function getUser() {
    try {
      let localStorageData = localStorage.getItem('app-user-store');
      if (localStorageData !== null) {
        localStorageData = JSON.parse(localStorageData);
        if (localStorageData.token !== null) {
          console.log('有token调接口校验token的可行性');
          checkToken(localStorageData.token, localStorageData.uuid);
        } else {
          console.log('这里是没有token走的调登录');
          getToken();
        }
      } else {
        getToken();
      }
    } catch (error) {
      console.error('getUser出现错误:', error);
    }
  }
  async function checkToken(token, uuid) {
    try {
      let params = {
        uuid: uuid,
        token: token,
        appId: 'h5_50000005'
      };
      let result = await post('/base/api/v1/valid', params);
      console.log(result.status, 'checkTokenstatus');

      if (result.data === null) {
        // 如果data为null，则执行getToken操作
        getToken();
      } else {
        // 如果data不为null，则执行getNewUrl操作
        let newUserData = {
          uuid: uuid,
          token: token,
          productId: stateForm.productId,
          tenantId: stateForm.tenantId,
          appid: 'h5_50000005'
        };
        localStorage.setItem('app-user-store', JSON.stringify(newUserData));
        getNewUrl();
      }

    } catch (error) {
      getToken();
      console.error('checkToken出现错误:', error);
    }
  }
  async function getToken() {
    try {
      let uuid = '';
      let token = '';
      const params = {
        sessionKey: stateForm.sessionKey,
        mobile: stateForm.mobile,
        appId: 'h5_50000005',
        withTenantIdFlag: false,
        mobileIsUserName: false,
        tenantId: stateForm.tenantId
      };
      let result = await post('/base/api/v1/open/login', params);
      console.log(result.status, 'getTokenstatus');
      if (result.status === 'success') {
        console.log(result, '登陆接口返回');
        uuid = result.data.uuid;
        token = result.data.token;
        let newUserData = {
          uuid: uuid,
          token: token,
          productId: stateForm.productId,
          tenantId: stateForm.tenantId,
          appid: 'h5_50000005'
        };
        localStorage.setItem('app-user-store', JSON.stringify(newUserData));
      getNewUrl()
      }
    } catch (error) {
      console.error('getToken出现错误:', error);
    }
  }

  async function getNewUrl() {
    try {
      const response = await post('/ppm/api/v2/built-in-system-ppm/wechat_auth_config/query/user_address', {
        userId: stateForm.userId
      });
      const result = response.data; // 获取响应数据
      console.log(result, '跳转地址');
      if (result.appUri) {
        window.location.href = result.appUri;
      }
    } catch (error) {
      // 请求失败时调用 getToken
      getToken();

      // 这里处理请求错误
      console.log('getNewUrl出现错误:', error);
    }
  }

  getTenantId();

  onBeforeRouteLeave(async (to, from, next) => {
    console.log('想跳登录'); // 打印消息
    await getTenantId();
    next(false); // 阻止路由跳转
  });
</script>
<style lang="less" scoped>
  .page_root {
      min-height: 100%;
      box-sizing: border-box;
  }
</style>